#include "bik_app.h"
#include "build.h"	
#include "gen_game_state.h"



#include "nextpeer/np_manager.h"

#ifdef _PLATFORM_IOS

#ifndef  PRO_VERSION
#include "inapppurchase/inapppurchasemanager.h"
#endif
#endif

#include "application/game_rms.h"
#include "resman/resman.h"
#include "lang/strman.h"
#include "script/file_list.h"

#include "num/rand.h"


#include "application/boot_loader.h"
#include "application/credit_state.h"


#include "console/console.h"
#include "font/font_manager.h"
#include "font/font.h"
#include "ui/ui_manager.h"
#include "ui/ui_skin.h"

#include "gameflow/game_flow_manager.h"
#include "gameflow/ui_state.h"
#include "gameflow/ui_popup.h"

//#include "bones/biped_instance.h"

#include "vfs/vfs.h"
#include "vfs/archive.h"

#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    
#include "util/timer.h"		    
#include <cassert>




using namespace gameflow;

static std::string	ForceLevel;
static void UpdateLoadCB(void* pData);




BIKApp::BIKApp (	WindowHandler*	pHandler, 
                const			std::string& Config, 
                const			std::string& Log) :
													GameApp(	pHandler, 
															Config, 
															Log),												
													m_DebugLoadingCount(0)
													
{
    
}

BIKApp::~BIKApp()
{
	 
}

bool      BIKApp::Shutdown()
{            

    NextPeerManager::Instance().ShutDown();
    return GameApp::Shutdown();
}

void		BIKApp::LoadArchives()
{

#ifdef _PLATFORM_ANDROID
	AdManager::Instance().RequestBannerAd();
#endif
    
	_LOG(MSG_COMMENT, "LOADING ARCHIVE ------------------------------------------");
	GetHandler()->UpdateOS();    

#if  defined(_PLATFORM_IOS) || defined(_PLATFORM_ANDROID)
	vfs::Archive* pArc = vfs::VFS::Instance().AddArchive("mt5.aac");
#else

//#ifdef  NDEBUG
	vfs::Archive* pArc = vfs::VFS::Instance().AddArchive("mt5.aac");
//#endif

	// use this block for unpacking data from archive
	if(pArc)
		pArc->Unpack("C:\\Users\\chan\\Desktop\\data2\\");

#endif
    

#ifndef _PLATFORM_IOS
//#ifdef NDEBUG
	 	
	/*
     // use this block to make an archive 


     vfs::Archive* pOutput = vfs::Archive::CreateArchive();
     script::FileList FL;

	 FL.Build("atlas/*.png");
	 FL.Build("atlas/*.lua");

     FL.Build("effects/*.*");
     FL.Build("fonts/*.*");     
     FL.Build("scripts/*.*");
     FL.Build("sounds/*.*");
     FL.Build("img/*.*");
	 FL.Build("ui/*.*");
	 FL.Build("ui_img/*.*");
	 FL.Build("localization/*.*");    	 
     
     for( int i = 0; i < FL.GetFileC(); i++)
     {
     std::string File =	FL.GetFileName(i);
     pOutput->AddFile(File);
     }
     pOutput->SaveArchive("mt5.aac");
	*/                                   
//#endif
#endif
  
}


void		BIKApp::OnCreateSplash()
{ 	
	GetHandler()->UpdateOS();
#ifdef WIN32
	BootLoader	Splash;
	Splash.AddPage("splash/2dstar_Entertainment_2.jpg", 
					1, 
					1, 
					2, 
					false,
					"",
					true
					);

	Splash.SetSpeedSkip(true);
	while (!Splash.IsDone())
	{
		Splash.Tick();
		Splash.Render();				
		//GetHandler()->UpdateOS();
	}	
#endif

	
    
}

void		BIKApp::OnBindKeys()
{
	GetHandler()->UpdateOS();
#if !defined(_PLATFORM_IOS) && !defined(_PLATFROM_ANDROID)
	console::Console::Instance().SetBackground("ui_img/black_bg.png");
	console::Console::Instance().PrintLastCommand(false);
	console::Console::Instance().Do("ReloadGame()");		// force it to reload the game scripts
	console::Console::Instance().BindKey(KEY_ESCAPE, "QuitGame()");
	console::Console::Instance().BindKey(KEY_F2, "CaptureAutoScreenshot()");
	console::Console::Instance().BindKey(KEY_F3, "CaptureMiniScreenshot()");
#endif
  	
}

//GameRMS*	BIKApp::CreateRMS()
//{
//	return new GameRMS::;
	//return new FIGVars();
//}

void		BIKApp::OnInitFonts()
{
	GetHandler()->UpdateOS();
	// we have done with graphic initialization , time to set loadupdate func
	 ui::UIManager::Instance().SetLoadCB(UpdateLoadCB, this); 
	
#ifdef _PLATFORM_WIN32
	const float FONT_WIDTH = 30.0f;
	const float FONT_HEIGHT = 30.0f;
#else
	const float FONT_WIDTH = 30.0f;
	const float FONT_HEIGHT = 30.0f;
#endif


	const float Scale = 1.0f; //(float)GetGraphics()->GetScreenWidth() / IPAD_WIDTH;
    
	FontManager::Instance().Init("",(int)(FONT_WIDTH * Scale), int(FONT_HEIGHT * Scale));
	Font* pFont = 
	FontManager::Instance().InitFont("smallfont","Pegasus", 8,16);
	FontManager::Instance().InitBitmapFont("smallfont", "fonts/smallfont.lua");
	FontManager::Instance().InitBitmapFont("tinyfont", "fonts/tinyfont.lua");
	FontManager::Instance().InitBitmapFont("storytext", "fonts/storytext.lua");
	FontManager::Instance().InitBitmapFont("mediumfont", "fonts/mediumfont.lua");
	FontManager::Instance().InitBitmapFont("bigfont", "fonts/bigbont.lua");
	FontManager::Instance().InitBitmapFont("gamefont", "fonts/gamefont.lua");
    
//#ifndef PRO_VERSION
	//FontManager::Instance().InitFont(	"SmallFont",
	//									"fonts/DroidSans.ttf",
	//									//"Droid Sans",
	//									(int)(FONT_WIDTH * Scale * 0.95f),
	//									int(FONT_HEIGHT * Scale));
//#else
	//FontManager::Instance().InitBitmapFont("smallfont", "fonts/smallfont.lua");
//#endif
    
	//pFont->SetBorder(true);


#ifdef _PLATFORM_WIN32
	//pFont = 
	//FontManager::Instance().InitFont(	"BigFont",
	//									"BankGothic Md BT",
	////									//"BankGothic Md BT",
	//									(int)(FONT_WIDTH * Scale ),
	//									int(FONT_HEIGHT * Scale * 1.2f));
#else

	//pFont =
	//FontManager::Instance().InitFont(	"BigFont",
	//									"fonts/bgothm.ttf",
	//									//"BankGothic Md BT",
	//									(int)(FONT_WIDTH * Scale ),
	//									int(FONT_HEIGHT * Scale * 1.2f ));
#endif



	

    //		console::Console::Instance().SetFont(pFont);
	_LOG(MSG_INIT, "Font manager initialized");
}

void		BIKApp::OnCreateStates()
{
#ifdef WIN32
	GetHandler()->UpdateOS();
#endif
	// register custom components
	//GENBGSmoke::Register();

	

    
    // register custom states
	LuaPlus::LuaState*	pScript = console::Console::Instance().GetScript();
	//audio::AudioManager::Register(pScript);
	GENGameState::Register(pScript);
	//GENVars::Register(pScript);
    //		GameSummary::Register(pScript);
    //		GENMetaState::Register(pScript);
    
    // load savegames
    
	
    
	m_CurrentRate = 0;
//#ifdef _PLATFORM_WIN32
//	m_TargetRate = 534;
//#else
	m_TargetRate = 21;
//#endif
    
    
    


#ifndef PRO_VERSION    
    // Loading Itune Store
    if(FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_IS_FULL_VERSION) == 0)
    {
        InAppPurchaseManager::Instance().LoadStore(FIGConstants::PRO_UPGRADE,
                                                   NULL
                                                   );
		std::string AD_KEY;		
		AD_KEY = FIGConstants::AD_WHIRL_KEY;		


		AdManager::Instance().RequestAd(FIGConstants::AD_WHIRL_KEY, this);



	}
#endif

    
	//GetHandler()->UpdateOS();
	
	
  
//#ifdef WIN32
//	ui::SpriteSet::Instance().SetDeferLoading(false);	// load immediately
//	ui::SpriteSet::Instance().SetClamp(1);	// load immediately		
//#else
	ui::SpriteSet::Instance().SetDeferLoading(true);	// find now, load later
	ui::SpriteSet::Instance().SetClamp(0);	// find now, load later
    res::ResMan::Instance().SetForceSkipInit(true);     // not to load into texture yet
//#endif
    
	
	ui::SpriteSet::Instance().LoadAtlas("atlas/atlas.lua");
	ui::SpriteSet::Instance().AddSet("img/sprites.lua");		
	ui::SpriteSet::Instance().AddSet("effects/sprites.lua");
	ui::SpriteSet::Instance().AddSet("ui_img/sprites.lua");

	  
    
	//ui::SpriteSet::Instance().SetDeferLoading(false);	// load immediately
	//ui::SpriteSet::Instance().SetClamp(1);	// load immediately		
	
	//ui::SpriteSet::Instance().SetDeferLoading(true);	// find now, load later
	//ui::SpriteSet::Instance().SetClamp(0);	// find now, load later
	
    
	// loaded for the bgedit
	//ui::SpriteSet::Instance().AddSet("decals/sprites2.lua");
	//ui::UISkin::Instance().Load("ui/test.skin");
    
    
	//lang::StrMan::Instance().LoadLangBin("localization/English.bin");
	 
//#ifdef WIN32
//#else
	ui::SpriteSet::Instance().SetDeferLoading(false);	// find immediately
	ui::SpriteSet::Instance().SetClamp(1);	// load immediately
    res::ResMan::Instance().SetForceSkipInit(false);     // load immediately
    

//#endif 
    
	//ui::UIManager::Instance().RefreshText();
#ifdef WIN32
	GetHandler()->UpdateOS();
#endif
	
	assert(m_pCamera && "No valid camera found");
	gameflow::GameFlowManager&	Game = gameflow::GameFlowManager::Instance();
	Game.SetCamera(m_pCamera);
    
	// load ios setting for tilt etc
	SetupUI();
	
	//ui::UIManager::Instance().RefreshText();

	
	std::string File;			
	File =	"ui/in_game.ui";

	Game.AddTransitionState("game", new GENGameState(m_pCamera,File,"",""));
	Game.TransitionToState("game",0.5f);



//#ifdef WIN32
//#else
	//res::ResMan::Instance().FlushTexturesExceptUI();
//#endif

	if(!g_pApp->GetRMS()->GetProfile())
	{
		g_pApp->GetRMS()->AddProfile("Neo","ENGLISH","mt5");	
	}

   	AUDIO().Init("sounds/soundbank.lua");
	AUDIO().SetSFXVolume((int)m_pRMS->GetSoundVolume());
	_LOG(MSG_INIT, "Audio manager Init");
	
    // we are done with you.
	ui::UIManager::Instance().SetLoadCB(NULL,NULL);
	  //		m_IsInitialized = true;
	m_CurrentRate = 0;	// done loading!
	_LOG(MSG_COMMENT ,"Loading Files Count is");
	_LOG(MSG_COMMENT ,m_DebugLoadingCount);
   
    
}

void		BIKApp::OnAdFullScreenShow()
{
	audio::BassAudio::Instance().PauseAll();
    
}

void        BIKApp::OnAdFullScreenDismissed()
{
	audio::BassAudio::Instance().RestartAll();
    
}

// UI Events

void	BIKApp::SetupUI()
{
	GameApp::SetupUI();   
}

static void UpdateLoadCB(void* pData)
{
//#ifndef PLATFORM_IOS
	//((MT5App*)pData)->GetHandler()->UpdateOS();
//#endif
    
	((BIKApp*)pData)->UpdateLoadBar(1);
    
//#ifndef PLATFORM_IOS
	((BIKApp*)pData)->GetHandler()->UpdateOS();
//#endif
    
	((BIKApp*)pData)->m_DebugLoadingCount++;
}




